/*
 * Auther:Guan Junming <junming.guan at kisters.cn> Created:12-Oct-2011 14:42:44 Company:Kisters AG
 */
package cn.eclass.servlet.front;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;

import cn.eclass.bean.api.ICategoryBean;
import cn.eclass.entity.AdvertiseEntity;
import cn.eclass.entity.CategoryEntity;
import cn.eclass.servlet.ActionFace;
import cn.eclass.utils.BeanFactory;
import cn.eclass.utils.ConstantsConf;

/**
 *
 * @author Guan Junming <junming.guan at kisters.cn>
 */
public class Index extends ActionFace {
	
    private static List<AdvertiseEntity> getAdEntities(String adCat) {
    	List<AdvertiseEntity> list = null;
    	try{
		    Map<String, Integer> adCatMap = BeanFactory.factory.getAdCatBean().getMap();
		    int catId = adCatMap.get(adCat);
		    list = BeanFactory.factory.getAdvertiseBean().getAdsByCat(catId);
	    } catch(Exception e) {
	    	e.printStackTrace();
	    }
    	
	    return list;
    }
    
    
    private static List<CategoryEntity> getL3CatList(CategoryEntity l1Cat, int rowNo) {
    	List<CategoryEntity> l3CatList = new ArrayList<CategoryEntity>();
    	List<CategoryEntity> l2CatList = l1Cat.getChildren();
    	for(CategoryEntity l2Cat : l2CatList) {
    		l3CatList.addAll(l2Cat.getChildren());
//    		for(CategoryEntity l3Cat : l3CatList) {
//    			
//    			int len = l3Cat.getName().length();
//    		}
    	}
//    	if(l3CatList.size()>maxNo) {
//    		for(int i = maxNo; i < l3CatList.size(); i++) {
//    			l3CatList.remove(i);
//    		}
//    	}
    	
    	List<CategoryEntity> catList = new ArrayList<CategoryEntity>();
    	int length = 0;
    	int index = 0;
    	for(;index < l3CatList.size(); index++) {
    		String name = l3CatList.get(index).getName();
    		int chLen = getLen(name);
    		if(chLen > ConstantsConf.catL3NameMaxLen_IndexPage) continue;
    		if(length + chLen > ConstantsConf.catLengthPerLine_IndexPage) break;
    		else {
        		length += chLen;
        		catList.add(l3CatList.get(index));
    		}
    	}
    	if(rowNo == 0) return catList;
    	// now row ==1,
    	length = 0;
    	catList = new ArrayList<CategoryEntity>();
    	for(; index < l3CatList.size(); index++) {
    		String name = l3CatList.get(index).getName();
    		int chLen = getLen(name);
    		if(chLen > ConstantsConf.catL3NameMaxLen_IndexPage) continue;
    		if(length + chLen > ConstantsConf.catLengthPerLine_IndexPage) break;
    		else {
        		length += chLen;
        		catList.add(l3CatList.get(index));
    		}
    	}
    	return catList;
    }
    
//    private static List<CategoryEntity> getL3CatList(CategoryEntity l1Cat, int max)
    
    private static int getLen(String str) {
    	char[] chArr = str.toCharArray();
    	int size = 0;
    	for(char ch : chArr) {
    		int len = 0;
    		int num = Character.getNumericValue(ch);
    		if(num <= 255 && num >=0) size+=1;
    		else size+=2;
    	}
    	return size;
    }
    
    //maxNo is the max number of thirdLevel categories to use under one first level category.
    //This function generates a map of: key-first level cat, value-third level cats.
    private static Map<String, List<CategoryEntity>> getMap(CategoryEntity root) {
    	Map<String, List<CategoryEntity>> map = new HashMap<String, List<CategoryEntity>>();
    	List<CategoryEntity> l1CatList = root.getChildren();
    	for(int i = 0; i < l1CatList.size(); i++) {
    		CategoryEntity cat = l1CatList.get(i);
    		String name = cat.getName();
//    		name.to
    		map.put(name+"_0", getL3CatList(cat, 0));
    		map.put(name+"_1", getL3CatList(cat, 1));
    	}
    	return map;
    }
    
   
    private static List<CategoryEntity> getL1CatListMod(List<CategoryEntity> l1CatListOri, CategoryEntity root) {
    	List<CategoryEntity> l1CatList = new ArrayList<CategoryEntity>();
        Map<String, List<CategoryEntity>> map = getMap(root);
        
    	for (int i = 0; i < l1CatListOri.size(); i++) {
    		CategoryEntity cat = l1CatListOri.get(i);
			String name = cat.getName();
			int chLen = getLen(name);
			List<CategoryEntity> subCatList = map.get(name+"_0");
			
			if(chLen <= ConstantsConf.catL1NameMaxLen_IndexPage && subCatList.size() >0) {
				l1CatList.add(cat);
				int size = l1CatList.size();
				if(size >= ConstantsConf.noL1Cats_IndexPage) {
					if(size % 2 !=0) l1CatList.remove(size - 1);
					break;
				}
			}
    	}

    	return l1CatList;
    }
    
    @Override
    public void doIndex() {
        try {
        	String adCat_onlineschool = "onlineschool";
        	String adCat_promotions = "promotions";
        	String adCat_intro = "intro";
        	String adCat_slideshow = "slideshow";
        	String adCat_ads0 = "ads0";
        	List<AdvertiseEntity> list_onlineschool = getAdEntities(adCat_onlineschool);
        	List<AdvertiseEntity> list_promotions = getAdEntities(adCat_promotions);
        	List<AdvertiseEntity> list_intro = getAdEntities(adCat_intro);        	
        	List<AdvertiseEntity> list_slideshow = getAdEntities(adCat_slideshow);     
        	List<AdvertiseEntity> list_ads0 = getAdEntities(adCat_ads0);  
        	
        	request.setAttribute("onlineschool", list_onlineschool);
        	request.setAttribute("promotions", list_promotions);
        	request.setAttribute("intro", list_intro);
        	request.setAttribute("slideshow", list_slideshow);
        	request.setAttribute("ads0", list_ads0);
        	
            ICategoryBean catBean = BeanFactory.factory.getCatBean();
            CategoryEntity root =  catBean.getRoot();
            int maxNoL3 = ConstantsConf.noL3Cats_IndexPage;
            int maxNoL1 = ConstantsConf.noL1Cats_IndexPage;
            List<CategoryEntity> l1CatList = root.getChildren();
            Map<String, List<CategoryEntity>> map = getMap(root); 
            List<CategoryEntity> l1CatListMod = getL1CatListMod(l1CatList, root);
            request.setAttribute("l1CatList", l1CatListMod);
            request.setAttribute("catMap", map);
            int maxRowNo = maxNoL1/2;
            if(l1CatListMod.size()/2 < maxRowNo) maxRowNo = l1CatListMod.size() / 2;
            request.setAttribute("catRowNo", maxRowNo);
        	
            request.getRequestDispatcher(view).forward(request, response);
            
        } catch (ServletException ex) {
            Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
